<template>
  <a-spin :spinning="loading">
    <a-form v-bind="formItemLayout">
      <a-row>
        <a-col :span="24">
          <a-form-item label="订单ID" v-bind="validateInfos.orderId">
            <a-input v-model:value="formData.orderId" placeholder="请输入订单ID" :disabled="true"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="用户ID" v-bind="validateInfos.userId">
            <a-input v-model:value="formData.userId" placeholder="请输入用户ID" :disabled="true"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="用户姓名" v-bind="validateInfos.userName">
            <a-input v-model:value="formData.userName" placeholder="请输入用户姓名" :disabled="true"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="服务人员ID" v-bind="validateInfos.nursesId">
            <div class="w-full flex flex-center justify-between">
              <a-input class="w-6/7" v-model:value="formData.nursesId" placeholder="请输入服务人员ID" :disabled="true"></a-input>
              <a-button type="primary" @click="openNurses">
                选择服务人员
              </a-button>
            </div>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="服务人员姓名" v-bind="validateInfos.nursesName">
            <a-input v-model:value="formData.nursesName" placeholder="请输入服务人员姓名" :disabled="true"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="监护人ID" v-bind="validateInfos.familyId">
            <a-input v-model:value="formData.familyId" placeholder="请输入监护人ID" :disabled="true"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="监护人姓名" v-bind="validateInfos.familyName">
            <a-input v-model:value="formData.familyName" placeholder="请输入监护人姓名" :disabled="true"></a-input>
          </a-form-item>
        </a-col>
        <!-- <a-col :span="24">
          <a-form-item label="创建人" v-bind="validateInfos.createBy">
            <a-input v-model:value="formData.createBy" placeholder="请输入创建人" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="创建日期" v-bind="validateInfos.createTime">
            <a-date-picker placeholder="请选择创建日期" v-model:value="formData.createTime" showTime
              value-format="YYYY-MM-DD HH:mm:ss" style="width: 100%" :disabled="disabled" />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="更新人" v-bind="validateInfos.updateBy">
            <a-input v-model:value="formData.updateBy" placeholder="请输入更新人" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="更新日期" v-bind="validateInfos.updateTime">
            <a-date-picker placeholder="请选择更新日期" v-model:value="formData.updateTime" showTime
              value-format="YYYY-MM-DD HH:mm:ss" style="width: 100%" :disabled="disabled" />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="状态" v-bind="validateInfos.status">
            <a-input v-model:value="formData.status" placeholder="请输入状态" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col> -->
        <a-col :span="24">
          <a-form-item label="佣金" v-bind="validateInfos.amt">
            <a-input-number v-model:value="formData.amt" placeholder="请输入佣金" style="width: 100%" :disabled="disabled" />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="备注" v-bind="validateInfos.remark">
            <a-textarea type="textarea" v-model:value="formData.remark" placeholder="请输入备注" :disabled="disabled"
              :rows="5" />
            <!-- <a-input v-model:value="formData.remark" placeholder="请输入备注" :disabled="disabled"></a-input> -->
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>

    <!-- 子表单区域 -->
    <!-- <a-tabs v-model:activeKey="activeKey" animated>
      <a-tab-pane tab="订单分配执行记录" key="nurseUserOrdersNursesExecute" :forceRender="true">
        <j-vxe-table :keep-source="true" resizable ref="nurseUserOrdersNursesExecuteTableRef"
          :loading="nurseUserOrdersNursesExecuteTable.loading" :columns="nurseUserOrdersNursesExecuteTable.columns"
          :dataSource="nurseUserOrdersNursesExecuteTable.dataSource" :height="340" :disabled="disabled"
          :rowNumber="true" :rowSelection="true" :toolbar="true" />
      </a-tab-pane>
    </a-tabs> -->
    
    <!-- iframe 护工选择弹窗 -->
    <a-modal
      :visible="nurseSelectModalVisible"
      title="选择护工"
      :width="1200"
      :footer="null"
      :bodyStyle="{ padding: '0', height: '80vh', overflow: 'hidden' }"
      :zIndex="2000"
      @cancel="handleCloseNurseModal"
      :maskClosable="false"
      :destroyOnClose="false"
    >
      <div class="nurse-select-container" style="width: 100%; height: 80vh;">
        <iframe
          v-if="nurseSelectModalVisible && nurseIframeSrc"
          ref="nurseIframeRef"
          :src="nurseIframeSrc"
          frameborder="0"
          class="nurse-select-iframe"
          style="width: 100%; height: 100%; border: none; display: block; background: white;"
        ></iframe>
        <div v-if="!nurseIframeSrc" style="padding: 20px; text-align: center; background: white;">
          正在加载护工选择页面...
        </div>
      </div>
    </a-modal>
  </a-spin>

</template>

<script lang="ts">
import { defineComponent, ref, reactive, computed, toRaw, onMounted, onBeforeUnmount } from 'vue';
import { defHttp } from '/@/utils/http/axios';
import { useValidateAntFormAndTable } from '/@/hooks/system/useJvxeMethods';
// import { queryNurseUserOrdersNursesExecuteListByMainId, queryDataById, saveOrUpdate } from '../NurseUserOrdersNurses.api';
// import { nurseUserOrdersNursesExecuteColumns } from '../NurseUserOrdersNurses.data';
import { Form } from 'ant-design-vue';
import { useMessage } from '/@/hooks/web/useMessage';
import { copyOrder } from '../NurseUserOrders.api';

const useForm = Form.useForm;
export default defineComponent({
  name: "NurseUserOrdersNursesForm",
  components: {
  },
  props: {
    formDisabled: {
      type: Boolean,
      default: false
    },
    formData: { type: Object, default: () => { } },
    formBpm: { type: Boolean, default: true }
  },
  emits: ['success'],
  setup(props, { emit }) {
    const loading = ref(false);
    const nurseSelectModalVisible = ref(false);
    const nurseIframeRef = ref(null);
    const nurseIframeSrc = ref('');
  
    // const nurseUserOrdersNursesExecuteTableRef = ref();
    // const nurseUserOrdersNursesExecuteTable = reactive<Record<string, any>>({
    //   loading: false,
    //   // columns: nurseUserOrdersNursesExecuteColumns,
    //   dataSource: []
    // });
    const activeKey = ref('nurseUserOrdersNursesExecute');
    const formData = reactive<Record<string, any>>({
      orderId: '',
      userId: '',
      userName: '',
      nursesId: '',
      nursesName: '',
      familyId: '',
      familyName: '',
      remark: '',
      amt: undefined,
      sysOrgCode: '', // 订单的机构代码
      hospital: '', // 订单的医院
    });

    //表单验证
    const validatorRules = reactive({
      orderId: [{ required: true, message: '请输入订单ID!' },],
      userId: [{ required: true, message: '请输入用户ID!' },],
      userName: [{ required: true, message: '请输入用户姓名!' },],
      nursesId: [{ required: true, message: '请输入服务人员ID!' },],
      nursesName: [{ required: true, message: '请输入服务人员姓名!' },],
      familyId: [{ required: true, message: '请输入监护人ID!' },],
      familyName: [{ required: true, message: '请输入监护人姓名!' },],
      createBy: [{ required: true, message: '请输入创建人!' },],
      createTime: [{ required: true, message: '请输入创建日期!' },],
      status: [{ required: true, message: '请输入状态!' },],
    });
    const { resetFields, validate, validateInfos } = useForm(formData, validatorRules, { immediate: false });
    // const dbData = {};
    const formItemLayout = {
      labelCol: { xs: { span: 24 }, sm: { span: 5 } },
      wrapperCol: { xs: { span: 24 }, sm: { span: 16 } },
    };

    // 表单禁用
    const disabled = computed(() => {
      if (props.formBpm === true) {
        if (props.formData.disabled === false) {
          return false;
        } else {
          return true;
        }
      }
      return props.formDisabled;
    });


    async function edit(row) {
      resetFields();
      Object.assign(formData, {
        userId: row.userId,
        userName: row.userName,
        nursesId: row.nursesId,
        nursesName: row.nursesName,
        familyId: row.familyId,
        familyName: row.familyName,
        orderId: row.id,
        remark: row.remark,
        sysOrgCode: row.sysOrgCode || '', // 保存订单的机构代码
        hospital: row.hospital || '', // 保存订单的医院
      });
      
      // 获取服务人员信息
      if (formData.orderId) {
        loading.value = true;
        try {
          const response = await defHttp.get({
            url: '/nurse_user_orders_nurses/nurseUserOrdersNurses/list',
            params: { orderId: formData.orderId }
          });
          const nurses = response.records;
          console.log('response ==', response);
          if (nurses.length > 0) {
            formData.nursesId = nurses[0].nursesId;
            formData.nursesName = nurses[0].nursesName;
            formData.remark = nurses[0].remark;
          }
        } catch (error) {
          console.error('获取服务人员信息失败', error);
        } finally {
          loading.value = false;
        }
      }
    }

    function openNurses() {
      console.log('=== 打开护工选择弹窗 ===');
      
      // 从当前订单数据中获取机构代码和医院
      const orgCode = formData.sysOrgCode || 'A01A03A01';
      const hospital = formData.hospital || '1';
      
      // 构建 iframe URL
      const iframeUrl = `https://anfine.huasun-healthcare.com/level/menu.html?orgCode=${orgCode}&id=${hospital}`;
      nurseIframeSrc.value = iframeUrl;
      
      console.log('iframe URL:', iframeUrl);
      console.log('订单机构代码:', orgCode);
      console.log('订单医院:', hospital);
      console.log('当前订单数据:', formData);
      
      // 打开弹窗
      nurseSelectModalVisible.value = true;
    }
    
    function handleCloseNurseModal() {
      nurseSelectModalVisible.value = false;
    }

    function setFieldsValue(values) {
      if (values) {
        Object.keys(values).map(k => {
          formData[k] = values[k];
        });
      }
    }

    /**
     * 值改变事件触发-树控件回调
     * @param key
     * @param value
     */
    function handleFormChange(key, value) {
      formData[key] = value;
    }

    let nursesId:string[] = [];
    let nursesName:string[] = [];
    let nursesPhone:string[] = [];
    let nursesIdcard:string[] = [];
    let nursesRatio:any[] = []; // 佣金比例

    // 监听来自 iframe 的消息
    function handleMessage(event) {
      console.log('收到 postMessage:', event.data);
      
      const { type, data } = event.data || {};

      if (type === 'nurse-selector-confirm') {
        console.log('确认选择护工，ID列表:', data);
        // 接收到确定消息，data 是选中的护工ID列表
        if (data && Array.isArray(data) && data.length > 0) {
          // 查询护工详细信息
          loadNurseDetails(data);
          
          // 关闭弹窗
          nurseSelectModalVisible.value = false;
        }
      } else if (type === 'nurse-selector-cancel') {
        // 接收到取消消息
        nurseSelectModalVisible.value = false;
      }
    }
    
    // 根据ID列表查询护工详细信息
    async function loadNurseDetails(ids) {
      try {
        console.log('开始查询护工详细信息，ID列表:', ids);
        
        // 清空数组并重新填充
        nursesId = [];
        nursesName = [];
        nursesPhone = [];
        nursesIdcard = [];
        nursesRatio = [];
        
        // 逐个查询护工信息（或者批量查询）
        for (const id of ids) {
          const response = await defHttp.get({
            url: '/nurse_nurses/nurseNurses/queryById',
            params: { id }
          });
          
          console.log(`查询护工 ${id} 的详细信息:`, response);
          
          if (response) {
            nursesId.push(response.id || id);
            nursesName.push(response.name || '');
            nursesPhone.push(response.phone || '');
            nursesIdcard.push(response.idcard || '');
            nursesRatio.push(response.ratio || 0);
          }
        }
        
        console.log('查询完成，护工详细信息:', {
          nursesId,
          nursesName,
          nursesPhone,
          nursesIdcard,
          nursesRatio
        });
        
        // 更新表单显示
        formData["nursesId"] = nursesId.toString();
        formData["nursesName"] = nursesName.toString();
        
        console.log('表单更新后:', {
          'formData.nursesId': formData.nursesId,
          'formData.nursesName': formData.nursesName
        });
      } catch (error) {
        console.error('获取护工详细信息失败:', error);
        const { createMessage } = useMessage();
        createMessage.error('获取护工详细信息失败');
      }
    }
    
    // 组件挂载时添加消息监听
    onMounted(() => {
      window.addEventListener('message', handleMessage);
    });
    
    // 组件卸载时移除监听
    onBeforeUnmount(() => {
      window.removeEventListener('message', handleMessage);
    });

    const { transformData } = useValidateAntFormAndTable(activeKey, {});

    async function getFormData() {
      await validate();
      return transformData(toRaw(formData))
    }

    async function submitForm() {
      // 暂时去掉重复提交限制
      // if(hasSend){
      //   const { createMessage } = useMessage();
      //   createMessage.warning("已分配服务人员，请勿重复提交");
      //   emit('closeModal');
      //   return
      // }

      const numOfNurses = nursesId.length;
      const { createMessage } = useMessage();
      
      try {
        loading.value = true;

        // 如果选择了多个服务人员
        if (numOfNurses > 1) {
          // 1. 调用复制订单接口
          const copyResponse = await copyOrder({ 
            id: formData.orderId, 
            num: numOfNurses - 1 
          });
          
          // 获取所有订单ID（从 newOrderIds 中获取）
          let allOrderIds = [];
          if (copyResponse && copyResponse.newOrderIds && Array.isArray(copyResponse.newOrderIds)) {
            // axios 会自动解包 result，直接从 copyResponse.newOrderIds 获取
            allOrderIds = copyResponse.newOrderIds;
          } else if (copyResponse && copyResponse.result && copyResponse.result.newOrderIds && Array.isArray(copyResponse.result.newOrderIds)) {
            // 兼容未解包的情况
            allOrderIds = copyResponse.result.newOrderIds;
          } else {
            // 如果接口返回格式不对，降级处理
            allOrderIds = [formData.orderId];
          }
          
          // 2. 为每个订单分配一个服务人员（根据 newOrderIds 的长度创建对应数量的记录）
          for(let i = 0; i < allOrderIds.length; i++) { 
            const mainData = await getFormData();
            // 确保数组索引不越界
            const nurseIndex = i < nursesId.length ? i : 0;
            const params = {
              status: '1',
              orderId: allOrderIds[i], // 使用对应的订单ID
              userId: mainData.userId,
              userName: mainData.userName,
              nursesId: nursesId[nurseIndex],
              nursesName: nursesName[nurseIndex],
              familyId: mainData.familyId,
              familyName: mainData.familyName,
              remark: mainData.remark,
              amt: mainData.amt
            };
            
            // 添加服务人员记录（不显示提示）
            await defHttp.post({ url: "/nurse_user_orders_nurses/nurseUserOrdersNurses/add", params }, { isTransformResponse: false, isShowMessage: false });
          }
          
          // 3. 将所有订单的 isapart 设置为 1，并写入护工信息和佣金比例（不显示提示）
          const currentTime = new Date().toISOString().slice(0, 19).replace('T', ' ');
          for (let i = 0; i < allOrderIds.length; i++) {
            const nurseIndex = i < nursesId.length ? i : 0;
            await defHttp.post({ 
              url: "/nurse_user_orders/nurseUserOrders/edit", 
              params: { 
                id: allOrderIds[i], 
                status: '10', 
                isapart: '1',
                nursename: nursesName[nurseIndex],
                nursephone: nursesPhone[nurseIndex],
                nurseidcard: nursesIdcard[nurseIndex],
                rate: nursesRatio[nurseIndex], // 写入佣金比例到价格参数
                updateTime: currentTime // 写入当前时间
              }
            }, { isTransformResponse: false, isShowMessage: false });
          }
          
        } 
        // 如果只选择了一个服务人员
        else {
          const mainData = await getFormData();
          const params = {
            status: '1',
            orderId: formData.orderId, // 使用原订单ID
            userId: mainData.userId,
            userName: mainData.userName,
            nursesId: nursesId[0],
            nursesName: nursesName[0],
            familyId: mainData.familyId,
            familyName: mainData.familyName,
            remark: mainData.remark,
            amt: mainData.amt
          };
          
          // 添加服务人员记录（不显示提示）
          await defHttp.post({ url: "/nurse_user_orders_nurses/nurseUserOrdersNurses/add", params }, { isTransformResponse: false, isShowMessage: false });
          
          // 将订单的 isapart 设置为 0，并写入护工信息和佣金比例（不显示提示）
          const currentTime = new Date().toISOString().slice(0, 19).replace('T', ' ');
          await defHttp.post({ 
            url: "/nurse_user_orders/nurseUserOrders/edit", 
            params: { 
              id: formData.orderId, 
              status: '10', 
              isapart: '0',
              nursename: nursesName[0],
              nursephone: nursesPhone[0],
              nurseidcard: nursesIdcard[0],
              rate: nursesRatio[0], // 写入佣金比例到价格参数
              updateTime: currentTime // 写入当前时间
            }
          }, { isTransformResponse: false, isShowMessage: false });
        }
        
        // 统一提示信息
        createMessage.success(`已成功分配 ${numOfNurses} 个服务人员${numOfNurses > 1 ? '，并拆分为 ' + numOfNurses + ' 个订单' : ''}`);
        
        emit('success');
      } catch (error) {
        // 不显示错误提示
      } finally {
        loading.value = false;
      }
    }
    return {

      validatorRules,
      validateInfos,
      activeKey,
      loading,
      formData,
      setFieldsValue,
      handleFormChange,
      formItemLayout,
      disabled,
      getFormData,
      submitForm,
      openNurses,
      handleCloseNurseModal,
      nurseSelectModalVisible,
      nurseIframeRef,
      nurseIframeSrc,
      edit
    }
  }
});
</script>

<style scoped>
.nurse-select-container {
  width: 100%;
  height: 100%;
  position: relative;
}

.nurse-select-iframe {
  width: 100%;
  height: 100%;
  border: none;
  display: block;
}
</style>